const app = getApp();
const url = "https://ynjksh.cn/api/",
domain ="https://ynjksh.cn/uploads/",
  trueDomain ="https://ynjksh.cn/";
const formatTime = date => { 
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const common = {
  post: function (option) {
    var that = this;
    var param = option.param;
    var method = option.method;
    if (common.empty(option.method)) { method = "GET"; }
    var url_request = url + option.module;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: url_request,
      method: method,
      data: option.param,
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      dataType: 'json',
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.meta.status == 1) {
            option.success(res.data);
          } else {
            option.fail();
            if (option.obj) {
              option.obj.setData({ errorMsg: res.data.meta.msg });
            }
            wx.showToast({
              title: res.data.meta.msg,
              icon: 'none',
              duration: 2000
            })
            return;
          }
        }
        else if (res.statusCode == 500) {
          tip.seriousError('服务器异常，请联系我们', '../pages/index/index');
          // wx.navigateBack();
          return;
        } else if (res.statusCode == 403) {
          tip.seriousError(res.data.message);
        }
        else {
          if (option.obj) {
            option.obj.setData({ errorMsg: '服务器异常，请联系我们' });
          } else {
            tip.seriousError('服务器异常，请联系我们', '../pages/index/index');
          }
          return;
        }
      },
      fail: function (data) {
        wx.hideLoading();
        var msg = data.msg ? data.msg : "请求超时"
        wx.showToast({
          title: msg,
          icon: 'loading',
          duration: 2000
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  //上传的
  uploadFile: function (option) {
    wx.uploadFile({
      url: url + storage.get("token"),
      header: {
        'content-type': 'multipart/form-data', // 默认值,
      },
      filePath: option.filePath,
      name: 'file',
      formData: { 'action': 'upload' },
      method: "POST",
      success: function (data) {
        if (data.statusCode == 200) {
          if (data.errMsg == 'uploadFile:ok') {
            option.success(JSON.parse(data.data).data);
          } else {
            tip.error('服务器无返回，请联系我们');
          }
        } else {
          tip.seriousError('服务器异常，请联系我们');
          return;
        }
      },
      fail: function (data) {
        tip.seriousError("与服务器通信失败，请联系我们");
        return;
      },
    })
  },
  //判断字符是否为空
  empty: function (str) {
    if (str == null) return true;
    if (str.length == 0) return true;
    if (str == '') return true;
    if (str == undefined) return true;
    return false;
  },
  //富文本编辑器转换
    /**
         * * WxParse.wxParse(bindName , type, data,target,imagePadding)
          * 1.bindName绑定的数据名(必填)
          * 2.type可以为html或者md(必填)
          * 3.data为传入的具体数据(必填)
          * 4.target为Page对象,一般为this(必填)
         */
  html: function (bindName = 'content',data ,target = that) {
    var WxParse = require('wxParse/wxParse.js');
    WxParse.wxParse(bindName, 'html', data, target,5);
  },
  //endregion
}
const user = {
  login: function (options) {
    if (wx.getStorageSync('session_access_token')) {
      wx.navigateTo({
        url: '../user/index',
      })
    } else {
      user.register(options);
    }
  },
  register: function (options) {
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.showLoading({ title: '正在登录', });
          wx.request({
            url: url + 'auth/wechat',
            data: { 'code': res.code },
            method: "POST",
            success: function (calback) {
              wx.hideLoading();
              if (calback.statusCode == 201) {//已经完善资料的
                if (calback.data.access_token) {
                  // console.log(calback.data.access_token);
                  let access_token = calback.data.access_token;
                  wx.setStorageSync('session_access_token', access_token);
                  wx.navigateTo({
                    url: '../user/index',//个人中心
                  });
                }
              }
              else {
                tip.error('请先完善信息', '../user/info?code=' + res.code, 'navigateTo');
              }
            },
            fail: function (data) {
              tip.seriousError('系统错误！');
            }
          })
        } else {
          tip.seriousError('code 不能为空');
        }
      }, fail: function (err) {
        tip.setting()
      }
    });
  }
}
const tip = {
  msg: function (title, reurl, locationType) {
    wx.showToast({
      title: title,
      duration: 2000,
      success: function (res) {
        if (reurl) {
          setTimeout(function () {
            if (locationType == 'reLaunch') {
              wx.reLaunch({
                url: reurl,
              })
            } else if (locationType == 'redirect') {
              wx.redirectTo({
                url: reurl,
              })
            } else if (locationType == 'switchTab') {
              wx.switchTab({
                url: reurl,
              })
            } else {
              wx.navigateTo({
                url: reurl,
              });
            }
          }, 2000)
        }
      }
    })
  },
  error: function (warningText, reurl, locationType) {
    wx.showModal({
      title: '温馨提示',
      content: warningText,
      showCancel: false,
      success: function (res) {
        if (reurl) {
          if (locationType == 'reLaunch') {
            wx.reLaunch({
              url: reurl,
            })
          } else if (locationType == 'redirect') {
            wx.redirectTo({
              url: reurl,
            })
          } else if (locationType == 'switchTab') {
            wx.switchTab({
              url: reurl,
            })
          } else {
            wx.navigateTo({
              url: reurl,
            });
          }
        }
      }
    })
  },
  success: function (successText, reurl, locationType) {
    wx.showModal({
      title: '操作成功',
      content: successText,
      showCancel: false,
      success: function (res) {
        if (reurl) {
          if (locationType == 'reLaunch') {
            wx.reLaunch({
              url: reurl,
            })
          } else if (locationType == 'redirect') {
            wx.redirectTo({
              url: reurl,
            })
          } else if (locationType == 'switchTab') {
            wx.switchTab({
              url: reurl,
            })
          } else {
            wx.navigateTo({
              url: reurl,
            });
          }
        }
      }
    })
  },
  confirm: function (msg, success) {
    wx.showModal({
      title: '确定要此操作吗？',
      content: msg,
      success: function (res) {
        if (res.confirm == true) {
          success();
        }
      },
      fail: function () {

      }
    })
  },
  seriousError: function (errorText, url) {
    wx.showModal({
      title: '系统提示！',
      content: errorText,
      showCancel: false,
      confirmText: "我知道了"
    })
  },
  setting: function (content, setting, success) {
    wx.showModal({
      title: '是否要打开设置页面重新授权',
      content: content,
      success: function (res) {
        if (res.confirm == true) {
          success();
        }
        else {
          tip.error('你拒绝了小程序授权，请删除小程序重试');
        }
      }
    })
  }
}
const regex = {
  mobile: function (mobile) {
    var regex = new RegExp(/^0?(13|14|15|17|18|19)[0-9]{9}$/, 'g');
    return regex.test(mobile);
  },
}
//设置缓存的
const storage = {
  set: function (key, data) {
    wx.setStorageSync(key, data);
  },
  get: function (key) {
    return wx.getStorageSync(key);
  },
  removeKey: function (key) {
    return wx.removeStorageSync(key);
  }
}
const ldtime = {
  //获取时间戳
  get: function () {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    return timestamp;
  },
  dataFormate: function (unixtime) {
    var dateTime = new Date(parseInt(unixtime) * 1000)
    var year = dateTime.getFullYear();
    var month = dateTime.getMonth() + 1;
    var day = dateTime.getDate();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    var second = dateTime.getSeconds();
    var now = new Date();
    var now_new = Date.parse(now.toDateString());  //typescript转换写法  
    var milliseconds = now_new - dateTime;
    var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
    return timeSpanStr;
  }
}
const weixin = {
  chooseLocation: function (options) {
    wx.authorize({
      scope: 'scope.userLocation',
      success: function () {
        wx.chooseLocation({
          success: function (res) {
            var address = { 'address_name': res.name, 'address_detail': res.address, 'address_latitude': res.latitude, 'address_longitude': res.longitude };
            options.success(address);
          },
        })
      },
      fail: function () {
        tip.error("你拒绝了获取地址，请点击右上角 - 关于 - 右上角 - 设置 - 地理位置 - 允许")
      },
    })
  },
  getLocation: function (options) {
    wx.getLocation({
      success: function (res) {
        options.success(res);
      },
    });
  }
}
const form = {
  checkbox: function () {
  },
}
const page = {
  /**
   * 分页函数,调用此方法的页面必须包含current_page、listInfo、httpLock
   * options.obj    页面对象,
   * options.param  post参数，必须带上current_page
   */
  init: function (options) {
    var that = options.obj
    var param = options.param
    common.post({
      'param': param,
      'success': function (data) {
        var list = that.data.current_page == 1 ? data.data.lists : that.data.listInfo.concat(data.data.lists);
        if (data.data.allpage <= that.data.current_page) {
          var httpLock = true;
          var noMoreHidden = false;
        } else {
          var httpLock = false;
          var noMoreHidden = true;
        }
        that.setData({ listInfo: list, httpLock: httpLock, noMoreHidden: noMoreHidden });
        if (options.success) {
          options.success(data);
        }
      }
    });
  },
  loadMore: function (options) {
    var that = options.obj;
    if (that.data.httpLock == false) {
      that.setData({ current_page: that.data.current_page + 1, httpLock: true });
      setTimeout(function () {
        that.loadData();
      }, 300)
    }
  }
}
module.exports = {
  common: common,
  tip: tip,
  regex: regex,
  storage: storage,
  ldtime: ldtime,
  user: user,
  weixin: weixin,
  page: page,
  url: url
}
